//
//  HMComposedController.swift
//  weibo10
//
//  Created by mac on 15/10/27.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class HMComposedController: UIViewController {
    private lazy var emotionView: HMEmotionView = HMEmotionView { [weak self](emoticon) -> () in
        self?.textView.insertEmotion(emoticon)
    }
    
    // MARK: - 加载视图层次
    override func loadView() {
        view = UIView()
        setupUI()
    }
    // MARK: -视图的生命周期
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // 监听通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    /// 注销通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 通知方法
    @objc private func keyBoardChanged(n: NSNotification) {
        // print(n)
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let offset = rect.origin.y - view.bounds.height
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        // 更新toolbar的约束
        toolbar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        // 动画
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: -添加表情
    @objc private func addEmotionClick() {

        // 默认inputView为nil
        textView.resignFirstResponder()
        // 系统自带的键盘呢不会释放掉，需先退掉键盘，再激活键盘
        textView.inputView = textView.inputView == nil ? emotionView :  nil
        textView.becomeFirstResponder()
    }
    // MARK: -添加图片
    @objc private func addPictureClick() {
        print("添加图片")
    }
    // MARK: -取消
    @objc private func cancel() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    // MARK: -发布微博
    @objc func sendStatus() {
        let text = textView.emoticontext
        NetworkTools.sharedTools.sendStatus(text) { (result, error) -> () in
            if error != nil {
                print("出错了")
                SVProgressHUD.showErrorWithStatus("发送失败，请重试!")
                return
            }
            
            self.cancel()
        }
    }
    
    // MARK: - 懒加载控件
    private lazy var toolbar = UIToolbar()
    private lazy var textView: UITextView = {
       let tv = UITextView()
        tv.textColor = UIColor.darkGrayColor()
        tv.font = UIFont.systemFontOfSize(18)
        // 垂直滚动
        tv.alwaysBounceVertical = true
        // 滚动时键盘退出
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        // 设置代理
        tv.delegate = self
        return tv
    }()
    private lazy var placeHolder: UILabel = UILabel(title: "分享新鲜事...", titleColor: UIColor.lightGrayColor(), fontSize: 18)
}
// MARK: -
extension HMComposedController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = true
        placeHolder.hidden = textView.hasText()
    }
}

// MARK: -设置UI
private extension HMComposedController {
    func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        // 准备导航栏
        prepareNavigationBar()
        // 准备toolbar
        prepareToolbar()
        // 准备文本视图
        prepareTextView()
    }
    /// 准备文本视图
    func prepareTextView() {
        // 添加
        view.addSubview(textView)
        textView.addSubview(placeHolder)
        // 布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        placeHolder.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    /// 准备toolbar
    func prepareToolbar() {
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        // 添加
        view.addSubview(toolbar)
        
        // 布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
        }
        
        // 给toolbar 添加子控件
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "addPictureClick"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "addEmotionClick"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"])
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolbar.items = items
        
    }
    /// 准备导航栏
    func prepareNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancel")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        // 标题视图
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        
        navigationItem.titleView = view
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(title: HMUserAcountViewModel.sharedUserAccount.userAccount?.screen_name ?? "", titleColor: UIColor.lightGrayColor(), fontSize: 13)
        /// 添加控件
        view.addSubview(titleLabel)
        view.addSubview(nameLabel)
        /// 布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view.snp_top)
            make.centerX.equalTo(view.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.centerX.equalTo(view.snp_centerX)
        }
    }
}